<template>
  <div class="settings page page_padding">
    <NavigateBar :showForwardButton="false" />
    <div class="row">
      <h1 class="tips">文件属性</h1>
    </div>
    <div class="row">
      <h3 class="tips">是否公开</h3>
      <SwitchButton v-model:active="isPublic" />
    </div>
    <br />
    <div class="row">
      <h1 class="tips">文件操作</h1>
    </div>
    <div class="row">
      <h3 class="tips">删除该文件</h3>
      <DeleteButton :onClick="deleteImage">确认删除</DeleteButton>
    </div>
  </div>
</template>

<script>
import { reactive, ref, toRefs, watch } from "vue";
import SwitchButton from "../components/SwitchButton.vue";
import NavigateBar from "../components/NavigateBar.vue";
import { apis, tipsPromiseHandler } from "../api";
import DeleteButton from "../components/DeleteButton.vue";
import { useRouter } from "vue-router";

export default {
  components: { SwitchButton, NavigateBar, DeleteButton },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.id = to.params.id;
    });
  },
  setup() {
    const data = reactive({
      id: null,
      imageDetail: null
    })
    const isPublic = ref(null)
    const router = useRouter()

    watch(isPublic, (newVal, oldVal) => {
      if (oldVal == null || data.imageDetail == null) return
      let promise = apis.setPublicToFileById(data.imageDetail?.file?.fid, newVal)
      tipsPromiseHandler(promise, null, () => {
        isPublic.value = oldVal
      })
    })

    const getImageDetail = () => {
      setTimeout(() => {
        if (data.id != null) {
          apis.getImageById(data.id).then(response => {
            let result = response.data.result
            data.imageDetail = result
            isPublic.value = result?.file?.fisPublic
          })
        }
      })
    }

    const deleteImage = () => {
      let promise = apis.deleteImageById(data.imageDetail?.iid)
      tipsPromiseHandler(promise, () => {
        router.push("/image")
      })
    }

    getImageDetail()
    return { ...toRefs(data), deleteImage, isPublic }
  }
}
</script>

<style scoped lang="less">
.settings {
  min-height: 100vh;
}

.row {
  display: flex;
  align-items: center;
  justify-content: space-between;

  & > h1 {
    flex: 1;
    letter-spacing: 2px;
  }

  & > h3 {
    flex: 1;
    font-weight: 300;
    letter-spacing: 2px;
  }
}
</style>